package com.lzh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzh.common.utils.AppJwtUtil;
import com.lzh.common.utils.Md5Util;
import com.lzh.common.utils.RandomUtil;
import com.lzh.user.entity.ApUser;
import com.lzh.user.mapper.ApUserMapper;
import com.lzh.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author lzh
 * @since 2021-06-24
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Resource
    private ApUserMapper apUserMapper;

    @Override
    public boolean register(ApUser apUser) {
        //随机生成一个盐值
        String salt = RandomUtil.random(10);
        apUser.setSalt(salt);
        //使用盐值对密码进行md5加密
        String pwd = Md5Util.toMD5(apUser.getPassword(), salt);
        //设置用户密码
        apUser.setPassword(pwd);
        int insert = apUserMapper.insert(apUser);
        if (insert != 0) {
            return true;
        }else return false;
    }

    @Override
    public Map<String, Object> login(ApUser apUser) {
        QueryWrapper<ApUser> queryWrapper = new QueryWrapper<>();
        //根据name字段查询用户表
        queryWrapper.eq("name",apUser.getName());
        ApUser user = apUserMapper.selectOne(queryWrapper);
        if (user == null) {
            return null;
        }
        //获取盐值
        String salt = user.getSalt();
        //将用户提交的密码进行md5加密
        String pwd = Md5Util.toMD5(apUser.getPassword(), salt);
        //判断用户提交的密码是否跟注册时的密码相同
        if (!pwd.equals(user.getPassword())) {
            return null;
        }
        //登录成功，颁发令牌
        HashMap<String, Object> userInfo = new HashMap<>();
        //使用jwt生成令牌
        String token = AppJwtUtil.createToken(user.getId().longValue());
        userInfo.put("token",token);
        user.setPassword("****");
        user.setSalt("");
        userInfo.put("user",user);
        return userInfo;
    }

}
